package com.cn.demo.springboot.shiro.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.cn.demo.springboot.shiro.entity.ShiroUser;
import com.cn.demo.springboot.shiro.service.IAuthRealmService;

public class AuthRealm extends AuthorizingRealm {
	private final static Logger log = LoggerFactory.getLogger(AuthRealm.class);
	public final static String CURRENT_USER = "CURRENTUSER";
	
    @Autowired
    private IAuthRealmService authRealmService;
    
    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    	
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        
        String username = utoken.getUsername(); ShiroUser user = null;
        
        user = authRealmService.findUserByAccount(username);
        
        ShiroUser shiroUser = new ShiroUser(user.getUserId().toString(), user.getUserName(), user.getPassword(), null);
        
        setSession(CURRENT_USER, shiroUser);
        
        return new SimpleAuthenticationInfo(shiroUser.getUserName(), shiroUser.getPassword(),getName());//放入shiro.调用CredentialsMatcher检验密码
    }

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		log.debug("doGetAuthorizationInfo");
		
		ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getSession().getAttribute(CURRENT_USER);
		
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
		
        info.addStringPermissions(authRealmService.getPermissions(shiroUser.getUserId()));//将权限放入shiro中.
        return info;
	}
	
    protected void setSession(Object key, Object value){  
        Subject currentUser = SecurityUtils.getSubject();  
        if(null != currentUser){  
            Session session = currentUser.getSession();  
            log.debug("Session默认超时时间为[" + session.getTimeout()/1000 + "]秒");  
            if(null != session){  
                session.setAttribute(key, value);  
            }  
        }  
    }
	
}
